<template>
  <div class="box" :class="type ==='customer' ? '' : 'customer'">
    <el-table v-loading="loading" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg" :expand-row-keys="expandKeys" :data="tableData" :height="tableHeight" :style="{ 'max-height': type === 'page' ? 'auto' : '500px' }" row-key="id" @expand-change="handlerExpand">
      <el-table-column type="expand">
        <template #default="props">
          <div class="child">
            <div class="tool">
              <div class="info">
                <div class="item">
                  <span class="label">创建时间:</span>
                  <span class="value">{{ props.row.createTime }}</span>
                </div>
                <div class="item">
                  <span class="label">其他信息:</span>
                  <span class="value">{{ props.row.otherInfo }}</span>
                </div>
              </div>
              <el-button type="primary" @click="handlerAddLog(props.row)">新建待办</el-button>
            </div>
            <InquiryProgressTable @refresh="getList" :ref="el => handdlerAddRef(el, props.row.id)" class="table" :inquiryId="props.row.id" />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="type === 'page'" prop="clientEmail" label="客户邮箱" width="180">  
        <template #default="{ row }">
          <span class="link" @click="handlerSearchEmail(row.clientEmail)">{{ row.clientEmail }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="type === 'page'" prop="clientName" label="客户名称" width="100" /> 
      <el-table-column prop="productName" label="产品名称" min-width="170" />  
      <el-table-column prop="productCode" label="产品编号" width="80" />  
      <el-table-column prop="num" label="数量" width="60" />
      <el-table-column prop="deliveryTime" label="交期" width="110" />
      <el-table-column prop="orderStatus" label="状态" width="140">
        <template #default="{ row }">
          <el-select @change="(e: any) => handlerChangeStatus(e, row)" v-model="row.inquiryStatus" placeholder="请选择状态">
            <el-option
              v-for="item in inquiryStatusList"
              :key="item.dictSort"
              :label="item.dictLabel"
              :value="item.dictSort"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="nextTime" label="下次跟进日期" width="110" />
      <el-table-column label="操作" width="330" fixed="right">
        <template #default="scope">
          <el-button plain type="primary" size="small" @click="handlerNavPrice(scope.row)">询价信息</el-button>
          <div class="button_con">
            <el-button plain type="primary" size="small" @click="handlerExpand(scope.row)">待办</el-button>
            <div class="badge" v-if="scope.row.waitHandleNum > 0">{{ scope.row.waitHandleNum }}</div>
          </div>
          <el-button plain type="primary" size="small" @click="handlerOpenFolder(scope.row)">文件库</el-button>
          <el-popover popper-class="inquiry_more" placement="bottom" trigger="hover">
            <template #reference>
              <el-button plain type="primary" size="small">
                更多
                <i class="iconfont icon-caret-down" />
              </el-button>
            </template>
            <div class="more">
              <el-button class="mb10" link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button link type="primary" size="small" @click="handleDel(scope.row)">删除</el-button>
              <el-button class="mt10" v-if="scope.row.clientId" link type="primary" size="small" @click="handleCommunication(scope.row)">沟通</el-button>
            </div>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination_con">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :total="pagination.total"
        small background layout="prev, pager, next"
      />
    </div>
    <AddModal v-model="showAddInquiry" ref="AddModalRef" id="addInquiryModal1" @close="getList" />
    <AddInquiryProgressModal editable v-if="logVisable" :data="logForm" @close="handlerLogClose" />
  </div>
</template>
  
<script lang="ts" setup>
import { ref, onMounted, defineAsyncComponent, defineProps, defineExpose } from 'vue';
import api from '/@/api/email/index';
import { useRoute, useRouter } from 'vue-router';
import { Local } from '/@/utils/storage';
import { openFolder } from '/@/utils/webView';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores';
import { LoadingSvg } from '/@/utils/loading';
import { useIMStore } from '/@/stores/im'

const imStore = useIMStore()

const AddModal = defineAsyncComponent(() => import('./addInquiryModal.vue'));
const InquiryProgressTable = defineAsyncComponent(() => import('./../inquiryProgress/index.vue'));
const AddInquiryProgressModal = defineAsyncComponent(() => import('./../inquiryProgress/addModal.vue'));

const props = defineProps({
  customerId: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: 'page'
  },
  queryForm: {
    type: Object,
    default: {}
  },
  inquiryStatusList: {
    type: Object,
    default: [],
  },
  inquiryStatusMap: {
    type: Object,
    default: {},
  }
});

const tableData = ref([]);
const AddModalRef = ref()
const showAddInquiry = ref(false);

const logVisable = ref(false);
const logForm = ref<any>({});
const expandKeys = ref<string[]>([]);
const route = useRoute();
const router = useRouter();
const stores = useEmail(pinia);
const loading = ref(false);

const tableHeight = ref<any>(null);
const processTables = ref<any>({});

const pagination = ref({
  page: 1,
  size: 10,
  total: 0
});

const handlerSearchEmail = (email: string) => {
  if (email) {
    router.push({
			path: 'home',
      query: {
        search: email
      }
		});
  }
};

/**
 *  查询是否有采购员
 * @param row 
 */
const handleCommunication = (row: any) => {
  api.im.getPurchaseer(row.id).then((res: any) => {
    console.log(res)
    if (res.code === 200) {
      if(res.data) {
        sendProcurementNotice(res.data, row)

      }
    }
  })
}

/**
 * 检查是否已向指定用户发送过相同的采购信息
 * @param userId 用户ID
 * @param inquiryId 询价ID
 * @param productCode 产品编号
 * @returns Promise<boolean> 是否已发送过
 */
async function checkDuplicateProcurementNotice(userId: any, inquiryId: string, productCode: string): Promise<boolean> {
  try {
    // 构建会话ID (C2C会话格式: C2C_用户ID)
    const conversationID = `C2C${userId.toString()}`
    
    // 获取与该用户的消息历史（最近50条消息）
    const messageResult = await imStore.getMessageList(conversationID)
    
    if (!messageResult || messageResult.code !== 0) {
      console.log('获取消息历史失败，跳过重复检查')
      return false
    }
    
    // 检查消息列表中是否有相同的采购通知
    const messages = imStore.messageList || []
    console.log(messages)
    
    for (const message of messages) {
      // 检查自定义消息类型
      if (message.type === 'TIMCustomElem' && message.payload) {
        try {
          const customData = JSON.parse(message.payload.data || '{}')
          
          // 检查是否是采购通知且产品编号相同
          if (customData.type === 'procurement_notice' && 
              customData.productCode === productCode) {
            console.log('发现重复的采购通知:', customData)
            return true
          }
        } catch (error) {
          // 忽略解析错误的消息
          continue
        }
      }
    }
    
    return false
  } catch (error) {
    console.error('检查重复发送时出错:', error)
    // 出错时不阻止发送
    return false
  }
}

async function sendProcurementNotice(userId: any, row: any) {
  // 检查是否已向该用户发送过相同的采购信息
  const isDuplicate = await checkDuplicateProcurementNotice(userId, row.id, row.productCode)
  const procurementData = {
    type: 'procurement_notice',
    title: '采购通知',
    content: '您有新的采购订单需要处理',  
    amount: row.num,
    deadline: row.deliveryTime,
    status: 'pending',
    productImg: row.productImg,
    productName: row.productName,
    productCode: row.productCode,
  }

  if (isDuplicate) {
    try {
      // 询问用户是否要重复发送
      await ElMessageBox.confirm(
        `检测到您已向该采购员发送过产品编号为 "${row.productCode}" 的采购通知。\n\n是否要重复发送？`,
        '重复发送确认',
        {
          confirmButtonText: '直接沟通',
          cancelButtonText: '继续发送',
          type: 'warning',
          dangerouslyUseHTMLString: false,
        }
      ).then(() => {
        console.log('直接沟通')
        router.push({
          path: '/chat',
        })
      }).catch(() => {
        console.log('继续发送')
        sendCustomMessage(procurementData, userId)
      })
    } catch (error) {
      // 用户取消发送
      console.log('用户取消重复发送')
      return
    }
  }else {
    sendCustomMessage(procurementData, userId)

  }
}

const sendCustomMessage = async (params: any, userId: any) => {
  try {
    const result = await imStore.sendCustomMessage(
      params,
      '采购通知：您有新的采购订单需要处理',
      userId.toString(),
      'C2C',
    )

    if (result.code === 0) {
      ElMessage.success('发送成功')
      router.push({
        path: '/chat',
      })
    }
    else {
      ElMessage.error('发送失败')
    }
  }catch (error) {
    ElMessage.error('发送失败')
    console.error(error)
  }
}

const handlerChangeStatus = async (e: number, row: any) => {
  try {
    let giveupReason: any = {};
    if (e === 100) {
      giveupReason = await ElMessageBox.prompt(
        '放弃',
        '放弃原因',
        { 
          inputPlaceholder: '请输入放弃原因',
          inputType: 'textarea',
          inputValidator: (value) => {
            if (!value || !value.trim()) {
              return '输入不能为空或全是空格';
            }

            if (value.length >= 100) {
              return '输入不能大于100字';
            }
            return true;
          },
        }
      );
    }
    const data = {
      ...row,
      inquiryStatus: e,
      giveupReason: giveupReason.value
    };
    const res = await api.inquiry.updateInquiry(data);
    if (res.code === 200) {
      ElMessage({ type: 'success', message: '操作成功' });
    }
    getList();
  } catch (error) {
    row.inquiryStatus = row._inquiryStatus;
  }
};

const handdlerAddRef = (el: any, id: string) => {
  if (el) {
    processTables.value[id] = el;
  }
};

const handlerExpand = (row: any) => {
  if (expandKeys.value.includes(row.id)) {
    expandKeys.value = expandKeys.value.filter(key => key !== row.id);
  } else {
    expandKeys.value.push(row.id);
  }
};

const getList = async () => {
  let params: any = {
    pageNum: pagination.value.page,
    pageSize: pagination.value.size,
    ...props.queryForm
  };

  if (params.name) {
    params.clientName = params.name;
  }

  loading.value = true;
  if (props.type === 'page') {
    const type = route.query.type;
    if (type === 'client') {
      params.clientEmail = stores.curAccount;
    }
  } else {
    params.clientId = props.customerId
  }
  // 后端account是必传的
  params.account = stores.curAccount;
  const res = await api.inquiry.getList(params);
  loading.value = false;
  if (res.code === 200) {
    tableData.value = res.data.map((item: any) => {
      return {
        ...item,
        _inquiryStatus: item.inquiryStatus
      }
    });
    pagination.value.total = res.total;
  }
};

const handleDel = async (row: any) => {
  ElMessageBox.confirm('确认删除吗?', { cancelButtonText: '取消', confirmButtonText: '确认' }).then(async () => {
    const res = await api.inquiry.delInquiry(row.id);
    if (res.code === 200) {
      ElMessage({ type: 'success', message: '操作成功' });
      getList();
    }
  });
};

// 询价
const handlerNavPrice = (row: any) => {
  router.push({
    path: `/offer`,
    query: {
      inquiryId: row.id,
      productName: row.productName,
      productCode: row.productCode,
      clientEmail: row.clientEmail,
      clientName: row.clientName,
    }
  });
};

const handlerAddLog = (row: any) => {
  logVisable.value = true;
  logForm.value = {
    inquiryId: row.id
  };
};

const handleEdit = async (row: any) => {
  showAddInquiry.value = true
  const { data } = await api.inquiry.inquiryInfo(row.id);
  AddModalRef.value.form = {
    id: data.id,
    clientId: data.clientId,
    inquiryRemark: data.inquiryRemark,
    extCode: data.productCode,
    referenceName: data.productName,
    type: data.type,
    referenceImg: data.productImg ? data.productImg.split(',') : [],
    deliveryTime: data.deliveryTime,
    remark: data.remark,
    num: data.num,
  }
  AddModalRef.value.fileList = data.productImg ? data.productImg.split(',').map((m: any) => ({ name: m.replace('http://yj-mail-1307961934.cos.ap-shanghai.myqcloud.com/', ''), url: m })) : []
};

const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  getList();
};

const handlerLogClose = () => {
  logVisable.value = false;
  const tableRef = processTables.value[logForm.value.inquiryId];
  if (tableRef) {
    tableRef.search();
  }
  getList();
};

const handlerOpenFolder = (row: any) => {
  const account = stores.curAccount;
  let path = '/' + account + '/' + row.clientEmail + '/' + row.id;
  const defaultFilePath = Local.get('defaultFilePath');
  openFolder(defaultFilePath, path);
};

onMounted(() => {
  getList();
  if (props.type === 'page') {
    const setTableHeight = () => {
      tableHeight.value = window.innerHeight - 130 // 80 为顶部距离，根据实际情况设置
    }
    setTableHeight()
    window.addEventListener('resize', setTableHeight);
  }
});

const search = () => {
  pagination.value.page = 1;
  getList();
};

defineExpose({ search });

</script>
<style lang="scss" scoped>
.box {
  padding: 0 20px;
  width: 100%;

  &.customer {
    padding: 0;
  }

  :deep(.el-table-fixed-column--right .cell) {
    overflow: visible;
  }  
}

.pagination_con {
  display: flex;
  justify-content: end;
  padding: 10px;
  background: #fff;
}

.btn_con {
  padding: 7px 10px;
}

.add_btn {
  display: flex;
  justify-content: right;
  align-items: center;
}

.row {
  margin-bottom: 10px;
}

.child {
  padding-left: 50px;
  padding-right: 10px;
}

.info {
  display: flex;
  margin-bottom: 20px;
  margin-top: 10px;
}

.tool {
  display: flex;
  justify-content: space-between;
}

.item { 
  margin-right: 40px;
  font-size: 14px;
  color: #353535;
  .label {
    font-weight:  bold;
  }

  .value {
    margin-left: 5px;
  }
}

.table {
  flex: 1;
}

.more {
  display: flex;
  flex-direction: column;
  :deep(.el-button) {
    width: 60px;
    margin-left: 0;
  }
}

.link {
  cursor: pointer;
  &:hover {
    color: #3B7AEE;
  }
}

.button_con {
  display: inline-block;
  position: relative;
  margin: 0 10px;

  .badge {
    position: absolute;
    background-color: #f56c6c;
    color: #fff;
    padding: 0 6px;
    height: 16px;
    line-height: 16px;
    border-radius: 8px;
    right: -8px;
    top: -8px;
  }
}
</style>
<style lang="scss">
.inquiry_more {
  width: 80px!important;
  min-width: 80px!important;
}
</style>